package handler

import (
	"cargo-admin/cache"
	"cargo-admin/models"
	"cargo-admin/pkg"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"gorm.io/gorm"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账户或密码不能为空",
		})
		return
	}

	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return

	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
	return
}

func UserAddRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	if uid == 0 || rid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户角色不能为空",
		})
		return
	}

	data := models.UserRole{

		Uid: uid,
		Rid: rid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	if nid == 0 || rid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "角色权限不能为空",
		})
		return
	}

	data := models.RoleNode{
		Model: gorm.Model{},
		Rid:   rid,
		Nid:   nid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))

	if uid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不能为空",
		})
		return
	}

	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE
		  user_roles.uid = 1
	*/

	var role models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid = ?", uid).
		Find(&role)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户权限展示成功",
		"data": role,
	})

}

func RoleNodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))

	if rid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不能为空",
		})
		return
	}

	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
		WHERE
		  role_nodes.rid = 1
	*/

	var node models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where("role_nodes.rid = ?", rid).
		Find(&node)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户权限展示成功",
		"data": node,
	})

}

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	var user []models.User
	redis_key := "user_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	var count int64
	models.DB.Model(&models.User{}).Count(&count)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "用户展示成功",
		"count": count,
		"data":  user,
	})
}

func UserDetail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	var user models.User
	redis_key := "user_detail" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).First(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户展示成功",
		"data": user,
	})
}
